import React, { Component } from 'react'
import { useRoutes } from 'react-router-dom';
import config from '@/config.js'
import themeStyles from './utils/themeStyles';
import _ from 'lodash'
import consoleUtil from './utils/consoleUtil';
import { RouteHistoryProvider } from '@/context/router/routerContext';
import GlobalEventListener from './listener/GlobalEventListener';
import FloatBall from '@/components/viewWidget/FloatBall/FloatBall';

let routers = []

// 渲染路由
function RouteElement() {
  if (routers.length === 0) {
    routers = parseRouterConfig(config.routersConfig)
  }
  const element = useRoutes(routers)
  return element
}

/**
 * 根据路由配置解析路由
 * @param {Array} routerConfig 
 * @returns {Array} rotues
 */
function parseRouterConfig(routerConfig) {
  consoleUtil.log('Route resolution begins')
  const routers = _.cloneDeep(routerConfig)
  const componentContext = require.context('@/pages', true, /\.(js|jsx)$/)
  const componentPaths = componentContext.keys()

  function getRouters(routerConfig) {
    for (let item of routerConfig) {
      if (item.element.indexOf('.js') < 0 && item.element.indexOf('.jsx') < 0) {
        if (componentPaths.includes(item.element + '/index.js')) {
          const Component = componentContext(item.element + '/index.js').default
          item.element = <Component />
        } else if (componentPaths.includes(item.element + '/index.jsx')) {
          const Component = componentContext(item.element + '/index.jsx').default
          item.element = <Component />
        }
      } else {
        if (componentPaths.includes(item.element)) {
          const Component = componentContext(item.element).default
          item.element = <Component />
        }
      }
      if (Array.isArray(item.children)) {
        getRouters(item.children)
      }
    }
  }
  getRouters(routers)
  consoleUtil.log('Route resolution is complete')

  return routers
}

export default class App extends Component {

  render() {
    themeStyles.init() //主题样式初始化
    return (
      <RouteHistoryProvider>
        <GlobalEventListener />
        <FloatBall />
        <RouteElement />
      </RouteHistoryProvider>
    )
  }
}
